package com.helpustotravel.model.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.helpustotravel.core.DAOBase;
import com.helpustotravel.model.jdo.Photo;

public class PhotoDAO extends DAOBase {

	public PhotoDAO(PersistenceManager pm) {
		super(pm);
	}
	
	public void addPhoto(Photo photo) {
		try {
			pm.makePersistent(photo);
		} finally {
			
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Photo> getPhotos(String travellerName) {
		Query query = pm.newQuery("select from " + Photo.class.getName() + 
				" where travellerName == travellerNameParam " + 
				"parameters String travellerNameParam");
		List<Photo> photos = (List<Photo>)query.execute(travellerName);
		
		return photos;
	}
	
	public String getProfilPhotoURL(String travellerName) {
		List<Photo> photos = this.getPhotos(travellerName);
		for(Photo photo : photos) {
			if(photo.isProfilPhoto()) {
				return photo.getPhotoUrl();
			}
		}
		return "";
	}
	
	public void setProfilPhoto(String travellerName, String blobkey) {
		List<Photo> photos = this.getPhotos(travellerName);
		if(photos.size() > 0) {
			for(Photo photo : photos) {
				if(photo.getBlobKey().equals(blobkey)) {
					photo.setProfilPhoto(true);
					pm.makePersistent(photo);
				} else {
					if(photo.isProfilPhoto()) {
						photo.setProfilPhoto(false);
						pm.makePersistent(photo);
					}
				}
			}
		}
	}
}
